<?php
use wepay\join\demo\common\SignUtil;
use wepay\join\demo\common\DesUtils;
/**
 * Class ApiService
 */
class ShopService extends BaseService
{
    private static $self = NULL;

    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }

        return self::$self;
    }

    private $status_msgs = NULL;
    private $mUser = NULL;
    private $mUserThird = NULL;
    private $mSupplier = NULL;
    private $mProduct = NULL;
    private $mLineQuery = NULL;
    private $mInquiry = NULL;
    private $mArticle = NULL;
    private $mInformation = NULL;
    private $mNotice = NULL;
    private $mCircle = NULL;
    private $mFeedback = NULL;
    private $mCollection = NULL;
    private $mLogisticsLine = NULL;
    private $mCustomize = NULL;
    private $mSupply = NULL;
    private $mForest = NULL;
    private $mProductCate = NULL;
    private $mProductBrand = NULL;
    private $mProductAttr = NULL;
    private $mRefund = NULL;
    private $mOrder = NULL;
    private $mOrderShipping = NULL;
    private $mCart = NULL;
    private $mAddress = NULL;
    private $mStorage = NULL;
    private $mHarbour = NULL;
    private $mHarbourNeed = NULL;
    private $mAds = Null;
    private $mDevice = NULL;
    private $mRegion = NULL;
    private $mProComment = NULL;
    private $mForestNeed = NULL;
    private $mStorageNeed = NULL;
    private $mHelpCenter = NULL;
    private $mCircleComment = NULL;
    private $mCircleLike = NULL;
    private $mVerify = NULL;
    private $mQuote = NULL;
    private $mOrderProduct = NULL;
    private $mShipping = NULL;
    private $mLogisticsStatus = NULL;
    private $mPayMode = NULL;
    private $mInvoice = NULL;
    private $mMessage = NULL;
    private $mSpec = NULL;
    private $mLevel = NULL;
    private $mArea = NULL;
    private $mVideo = NULL;
    private $mPlace = NULL;
    private $mProductPic = NULL;
    private $client = NULL;
    private $mCircleReply = NULL;
    private $mVersion = NULL;
    private $mOpinion = NULL;
    private $mPosUser = NULL;
    private $mPurchaseResource = NULL;
    private $mNewResource = NULL;
    private $mAdProduct = NULL;
    private $mInviteCode        = NULL;

    public function __construct()
    {
        $this->status_msgs = ProfessionErrorCodeEnum::$status_msgs;
        $this->mUser = new Involved_UserModel();
        $this->mUserThird = new Involved_UserThirdModel();
        $this->mSupplier = new Involved_SupplierModel();
        $this->mProduct = new Involved_ProductModel();
        $this->mLineQuery = new Involved_LineQueryModel();
        $this->mInquiry = new Involved_InquiryModel();
        $this->mArticle = new Involved_ArticleModel();
        $this->mInformation = new Involved_InformationModel();
        $this->mNotice = new Involved_NoticeModel();
        $this->mCircle = new Involved_CircleModel();
        $this->mFeedback = new Involved_FeedbackModel();
        $this->mCollection = new Involved_CollectionModel();
        $this->mLogisticsLine = new Involved_LogisticsLineModel();
        $this->mCustomize = new Involved_CustomizeModel();
        $this->mSupply = new Involved_SupplyModel();
        $this->mForest = new Involved_ForestModel();
        $this->mProductCate = new Involved_ProductCateModel();
        $this->mProductBrand = new Involved_ProductBrandModel();
        $this->mProductAttr = new Involved_ProductAttrModel();
        $this->mRefund = new Involved_RefundModel();
        $this->mOrder = new Involved_OrderModel();
        $this->mOrderShipping = new Involved_OrderShippingModel();
        $this->mCart = new Involved_CartModel();
        $this->mAddress = new Involved_AddressModel();
        $this->mArticle = new Involved_SupplierModel();
        $this->mStorage = new Involved_StorageModel();
        $this->mForest = new Involved_ForestModel();
        $this->mHarbour = new Involved_HarbourModel();
        $this->mHarbourNeed = new Involved_HarbourNeedModel();
        $this->mAds = new Involved_AdsModel();
        $this->mDevice = new Involved_DeviceModel();
        $this->mRegion = new Involved_RegionModel();
        $this->mProComment = new Involved_ProCommentModel();
        $this->mForestNeed = new Involved_ForestNeedModel();
        $this->mStorageNeed = new Involved_StorageNeedModel();
        $this->mVerify = new Involved_VerifyModel();
        $this->mHelpCenter = new Involved_HelpCenterModel();
        $this->mCircleComment = new Involved_CircleCommentModel();
        $this->mCircleLike = new Involved_CircleLikeModel();
        $this->mQuote = new Involved_QuoteModel();
        $this->mOrderProduct = new Involved_OrderProductModel();
        $this->mShipping = new Involved_ShippingModel();
        $this->mLogisticsStatus = new Involved_LogisticsStatusModel();
        $this->mPayMode = new Involved_PayModeModel();
        $this->mInvoice = new Involved_InvoiceModel();
        $this->mMessage = new Involved_MessageModel();
        $this->mSpec = new Involved_SpecModel();
        $this->mLevel = new Involved_LevelModel();
        $this->mArea = new Involved_ProducingAreaModel();
        $this->mVideo = new Involved_VideoModel();
        $this->mPlace = new Involved_PlaceModel();
        $this->mProductPic = new Involved_ProductPicModel();
        $this->mCircleReply = new Involved_CircleReplyModel();
        $this->mVersion = new Involved_VersionModel();
        $this->mOpinion = new Involved_OpinionModel();
        $this->mPosUser = new Involved_PosUserModel();
        $this->mMobile = new Involved_MobileModel();
        $this->mPurchaseResource = new Involved_PurchaseResourceModel();
        $this->mNewResource = new Involved_NewResourceModel();
        $this->mAdProduct = new Involved_AdProductModel();
        $this->mInviteCode          =   new Involved_InviteCodeModel();
    }

    /**
     * 参数验证
     * @param $obj
     * @param $arr
     * @author alice
     * @date 2016-1-13
     * @return bool
     * @return bool
     */
    public function  checkProperties($obj, $arr)
    {
        if (empty($arr)) return true;
        $obj = (array)$obj;

        foreach ($arr as $v) {
            if (is_null($obj[$v])) {
                return false;
            }
        }
        return true;
    }


    /**
     * 获取首页数据
     * @author  fyl
     * @date    2016-6-22
     * @return array
     * @throws Exception
     */
    public function GetIndex()
    {
        #获取广告位列表
        $ads = $this->mAds->GetAdsList(AdEnum::AD_TYPE_INDEX_PC_BANNER);
        $ads_log = $this->mAds->GetAdsList(AdEnum::AD_TYPE_INDEX_LOG);
        $ads_slab = $this->mAds->GetAdsList(AdEnum::AD_TYPE_INDEX_SLAB);
        $ads_domestic = $this->mAds->GetAdsList(AdEnum::AD_TYPE_INDEX_DOMESTIC);

        #获取产品列表
        $products_log       = $this->mProduct->GetindexList(CateEnum::CATE_TYPE_LOG, 8);            //进口原木列表
        $products_slab      = $this->mProduct->GetindexList(CateEnum::CATE_TYPE_SLAB, 8);            //锯材列表
        $products_domestic = $this->mProduct->GetindexList(CateEnum::CATE_TYPE_DOMESTIC,8);            //国产原木列表
        //$products_art      = $this->mProduct->GetindexList(CateEnum::CATE_TYPE_ART, 8);            //艺术品列表

        #返回数据
        return [
                'ads'                 => $ads,
                'ads_log'             => $ads_log,
                'ads_slab'            => $ads_slab,
                'ads_domestic'        => $ads_domestic,
                'products_log'        => $products_log,
                'products_slab'       => $products_slab,
                'products_domestic'  => $products_domestic,
                //'products_art'        => $products_art,

        ];
    }

    /**
     * 首页新闻列表展示
     * @return mixed
     * @author fyl
     * @date 16-04-01
     */
    public function  GetIndexinformation()
    {
        $information = $this->mInformation->InformationList(InformationEnum::IN_TYPE_TOP_LINE);
        $conjuncture = $this->mInformation->InformationList(InformationEnum::IN_TYPE_CULTURE);
        return [
          "information" =>  $information,
          "conjuncture" =>  $conjuncture,
        ];
    }

    /*-----------------------------------------------------注册-------------------------------------------------------*/

    /**
     * 验证手机号
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckMobile($paramObj)
    {
        return $this->mUser->JsCheckMobile($paramObj->mobile);
    }

    /**
     * 短信验证
     * @param $paramObj
     * @return int
     */
    public function JsCheckNews($paramObj)
    {
        $info = session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        $time = time() - $info['time'];
        if ($info['news_captcha'] == $paramObj->news_captcha && $info['mobile'] == $paramObj->mobile) {
            if ($time <= 600) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return 3;
        }
    }

    public function JsCheckCaptcha($paramObj)
    {
        if(strtolower($paramObj->captcha) == strtolower(Session::get('mt_Captcha'))){
            return 1;
        }else{
            return 2;
        }
    }

    /**
     * 发送短信验证
     * @param $paramObj
     * @return string
     */
    public function VerifyNews($paramObj)
    {
        $info = session_get(UserEnum::CLIENT_NEWS_CAPTCHA);

        if (time() - $info['time'] < 60 && $paramObj->mobile == $info['mobile']) {
            return 10001;
        } else {
            #接受参数
            $aData["mobile"] = $paramObj->mobile;
            #生成随机验证码
            $news_captcha = substr(str_shuffle("012345678901234567890123456789"), 0, 6);
            #发送参数
            $data = $this->mMobile->sendTemplateSMS($paramObj->mobile, array($news_captcha, '10'), 98926);
            if ($data == 10000) {
                $aData['time'] = time();
                $aData['news_captcha'] = $news_captcha;
                Session::put(UserEnum::CLIENT_NEWS_CAPTCHA, $aData);
                return 10000;
            } elseif ($data == 160040) {
                return 160040;
            }

        }
    }


    /**
     * 用户注册
     * @param $paramObj
     * @author fyl
     * @date 2016-5-04
     * @return mixed
     * @throws Exception
     */
    public function DeposeRegister($paramObj)
    {
        #参数验证
        $check = $this->checkProperties($paramObj, ['mobile', 'password']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #手机号验证
        if (!preg_match('/^1[34578]\d{9}$/', $paramObj->mobile)) {
            throw new Exception("手机号码错误", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }

        #手机号是否已注册
        $mobile = $this->mUser->GetMobile($paramObj->mobile);
        if ($mobile !== 0) {
            throw new Exception("手机号已注册", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #注册用户
        $aDate = [
            'mobile' => $paramObj->mobile,
            'user_name' => $paramObj->user_name,
            'password' => md5($paramObj->password),
            'corporation' => $paramObj->corporation,
            'created' => time(),
        ];
        $user_id = $this->mUser->insert($aDate);

        #是否注册成功
        if (!$user_id) {
            throw new Exception("注册失败", ProfessionErrorCodeEnum::ERROR_DB_UPDATE);
        } else {
            #返回用户信息
            $user_info = $this->mUser->GetUserInfo($user_id);
            session_put(UserEnum::USER_INFO_USER_ID, $user_info->user_id);
            session_put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
            return 1;
        }
    }

    /**
     * 重置密码
     * @param $paramObj
     * @author fyl
     * @date 2016-6-28
     * @return mixed
     * @throws Exception
     */
    public function ModifyPwd($paramObj)
    {
        #参数验证
        $check = $this->checkProperties($paramObj, ['mobile', 'password']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #修改密码
        $aDate = [
            'password' => md5($paramObj->password),
        ];
        $user_id = $this->mUser->update($aDate,['mobile'=>$paramObj->mobile]);

        #是否注册成功
        if (!$user_id) {
            throw new Exception("修改失败", ProfessionErrorCodeEnum::ERROR_DB_UPDATE);
        } else {
            return 1;
        }
    }

/*---------------------------------------------------------登录-----------------------------------------------------*/
    /**
     * 验证用户名
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckUser($paramObj)
    {
        return $this->mUser->JsCheckUser($paramObj->username);
    }

    /**
     * 验证密码
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckPwd($paramObj)
    {
        return $this->mUser->JsCheckPwd($paramObj->username,md5($paramObj->pwd));
    }

    /**
     * 登陆验证
     * @param $user
     * @return mixed
     * @throws Exception
     */
    public function VerifyLogin($user)
    {
        #此处只做简单验证
        if(empty($user->username) || empty($user->password)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #数据验证
        $user_info = $this->mUser->login($user->username,md5($user->password));

        if(!$user_info){
            throw new Exception('用户名或密码错误', ProfessionErrorCodeEnum::ERROR_PASSWORD_WRONG);
        }
        #存储SESSION
        Session::put(UserEnum::USER_INFO_USER_ID, $user_info->user_id);
        Session::put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
        Session::put('times',time());
        return $user_info;

    }

   /**
     *查询登陆错误信息
     * @param $user_name
     * @param $mobile
     * @return mixed
     */
 /*   public function LoginTime($user_name,$mobile)
    {
        return $this->mLockLogin->LoginTime($user_name,$mobile);
    }*/

    /**
     * 用户注销
     * @return bool
     * @throws Exception
     * @author fyl
     * @data   2016-5-10
     */
    public function Logout()
    {
        #验证登录
        if (!session_has(UserEnum::USER_INFO_SESSION_KEY))
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        #清空SESSION
        Session::flush();
        return 1;
    }
    #采购信息
    public function  PurchaseResource(){

        return  $this->mPurchaseResource->PurchaseResource();
    }
    #采购信息(个人中心)
    public function  PurchaseResourceAdmin(){

        return  $this->mPurchaseResource->PurchaseResourceAdmin();
    }
    #采购信息删除(个人中心)
    public function  UserPurchaseResourceDel($purchase_id){

        return  $this->mPurchaseResource->PurchaseResourceDel($purchase_id);
    }

    #首页采购信息
    public function  IndexPurchaseResource(){

        return  $this->mPurchaseResource->IndexPurchaseResource();
    }

    #采购信息查询
    public function  SelectPurchase($paramObj){

        return  $this->mPurchaseResource->SelectPurchase($paramObj);
    }
    #发布采购
    public function AddPurchase($paramObj){
        $aData = [
            'title'      => $paramObj->title,
            'spec'       => $paramObj->spec,
            'num'             => $paramObj->num,
            'unit'              => $paramObj->unit,
            'price'             => $paramObj->price,
            'place'             => $paramObj->place,
            'address'           => $paramObj->address,
            'sign'         => $paramObj->sign,
            'contacts'       => $paramObj->contacts,
            'tell'       => $paramObj->tell,
            'company'       => $paramObj->company,
            'created'           => time(),
            'state'         => 0,
            'user_id'         => session_get(UserEnum:: USER_INFO_USER_ID),
        ];
        return $this->mPurchaseResource->AddPurchase($aData);

    }
    //商城页
    public function Shopping($paramObj){
        return $this->mProduct->Shopping($paramObj);
    }
    //首页进商城页
    public function Shopping_Index1($category){
        return $this->mProduct->Shopping_Index1($category);

    }
    //首页进商城页
    public function Shopping_Index2($quality){
        return $this->mProduct->Shopping_Index2($quality);

    }
    //商城页
    public function ShoppingNull(){
        return $this->mProduct->ShoppingNull();
    }
    public function yiji(){
        return $this->mProductCate->yiji();
    }
    public function erji($parent_id){
        return $this->mProductCate->erji($parent_id);
    }
    public function sanji($parent_id){
        return $this->mProductCate->sanji($parent_id);
    }
//四大分类
    public function ShoppingFour($id){
         if($id == 17){
                 $data       =$this->mProduct->ShoppingFour(CateEnum::CATE_TYPE_LOG);            //原木列表
            }elseif($id == 102){
                 $data       =$this->mProduct->ShoppingFour(CateEnum::CATE_TYPE_SLAB);//板材列表
            }elseif($id == 154){
                 $data       =$this->mProduct->ShoppingFour(CateEnum::CATE_TYPE_FURNITURE);//家具列表
            }else{
                $data        =$this->mProduct->ShoppingFour(CateEnum::CATE_TYPE_ART);  //艺术品列表
            }
            return $data;


    }
    //商城关键词搜索
    public function SelectKeyword($name){
        return $this->mProduct->SelectKeyword($name);
    }
    //商城关键词搜索
    public function IndexKeyword($top,$name){
        if($top==1){
            $paramObj                   =          new stdClass();
            $paramObj->key_word         =          $name;
            $paramObj->sort_order       =          "";

            return $this->mProduct->Shopping($paramObj);
        }else{
            $paramObj                   =          new stdClass();
            $paramObj->key_word         =          $name;
            return $this->mNewResource->NewResourceList($paramObj);
        }

    }

    /**
     *现货列表
     */
    public function NewResource($paramObj){

        return $this->mNewResource->NewResourceList($paramObj);
    }

    /**
     * 现货详情
     */
    public function NewResourceDetails($paramObj){
        $details = $this->mNewResource->NewResourceDetails($paramObj);
        $details_pic = $this->mProductPic->DetailsPic($paramObj);
        return [
        'details'      =>     $details,
        'details_pic'  =>     $details_pic
        ];
    }

    /**
     * 发布定制单
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function PublishCustomize($paramObj)
    {
        #保存数据
        $aData = [
            'contact'       =>  $paramObj->contact,
            'mobile'        =>  $paramObj->mobile,
            'description'   =>  $paramObj->description,
            'created'       =>  time()
        ];
        if($this->mCustomize->insert($aData)){
            return  1;
        }
    }
    /**
     * 商城原木板材详情页
     */
    public function ShoppingDetails($product_id){
        return $this->mProduct->ShoppingDetails($product_id);

    }
    /**
     * 商城家具工艺品详情页
     */
    public function ShoppingDetails2($product_id){
        return $this->mProduct->ShoppingDetails2($product_id);

    }
    //资讯列表
    public function InformationList($cate){
        return $this->mInformation->InformationList1($cate);

    }
    public function InformationDetails($id){
        return $this->mInformation->GetNewsById($id);

    }

    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 用户信息修改
     */
    public function UserAccountModify($paramObj){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $check = $this->checkProperties($paramObj, ['user_name', 'corporation']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if(empty($paramObj->avatar)){
            $paramObj->avatar = $paramObj->old_avatar;
        }
        $aData = [
            "phone" => $paramObj->phone,
            "user_name" => $paramObj->user_name,
            "corporation" => $paramObj->corporation,
            "address" => $paramObj->address,
            "avatar" => $paramObj->avatar,
        ];
        $this->mUser->update($aData,['user_id'=>$user_id]);
       $user_info = $this->mUser->getUserInfo($user_id);
        Session::put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
        return 1;

    }
    public function UserPasswordSelect($user_id,$old_password){
        $old_password=md5($old_password);
        return $this->mUser->UserPasswordSelect($user_id,$old_password);

    }
    public function UserPasswordUpdate($new_pass, $user_id){
        return $this->mUser->ModifyPassword($new_pass, $user_id);

    }
    public function UserReceiptAddress($user_id){
        return $this->mAddress->GetAddressList($user_id);


    }

    /**
     * @param $user_id
     * @return int
     * @throws Exception
     * 个人现货列表
     */
    public function UserNowResourceAdmin($user_id){
        return $this->mNewResource->UserNowResourceList($user_id);
    }

    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 个人现货列表删除
     */
    public function NowResourceDelete($paramObj){
        return $this->mNewResource->delete(['product_id' => $paramObj->product_id]);
    }

    /**
     * 现货添加
     * @param $paramObj
     * @return bool
     * @throws Exception
     * @date 2016-06-30
     */
    public function UserAddNowResource($paramObj)
    {
        #登录验证
        if (!session_has(UserEnum::USER_INFO_SESSION_KEY))
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $check = $this->checkProperties($paramObj, ['product_name', 'spec', 'place', 'storage', 'start_num', 'description', 'price', 'contact', 'contact_name', 'address', 'company', 'unit']);
        if (!$check) {
            return false;
        }
        if($paramObj->product_img){
            $paramObj->product_img =  QiniuUpload::instance()->upload_files($paramObj->product_img);
        }
        if($paramObj->show_img1){
            $paramObj->show_img1 =  QiniuUpload::instance()->upload_files($paramObj->show_img1);
        }
        if($paramObj->show_img2){
            $paramObj->show_img2 =  QiniuUpload::instance()->upload_files($paramObj->show_img2);
        }
        $data = [
            'product_name'  => $paramObj->product_name,
            'spec'          => $paramObj->spec,
            'place'         => empty($paramObj->place)?'':$paramObj->place,
            'storage'       => empty($paramObj->storage)?'':$paramObj->storage,
            'stock'         => $paramObj->stock,
            'start_num'     => empty($paramObj->start_num)?'':$paramObj->start_num,
            'product_img'   => empty($paramObj->product_img)?'':$paramObj->product_img,
            'description'   => empty($paramObj->description)?'':$paramObj->description,
            'price'         => $paramObj->price,
            'level'         => $paramObj->level,
            'user_id'       => $user_id,
            'created'       => time(),
            'contact'       =>  empty($paramObj->contact)?'':$paramObj->contact,
            'contact_name'  =>  empty($paramObj->contact_name)?'':$paramObj->contact_name,
            'address'       =>  empty($paramObj->address)?'':$paramObj->address,
            'company'       =>  empty($paramObj->company)?'':$paramObj->company,
            'unit'          =>  empty($paramObj->unit)?'':$paramObj->unit,
        ];

            $product_id = $this->mNewResource->insert($data);

        if(!$product_id)
            return false;

        #插入产品媒体库
        $aData = [
            'resource_id' => empty($paramObj->product_id) ?$product_id: $paramObj->product_id,
            'show_img2' => empty($paramObj->show_img1) ?'' : $paramObj->show_img1,
            'show_img3' => empty($paramObj->show_img2) ? '' : $paramObj->show_img2,
            'show_img1' => empty($paramObj->product_img) ? '' : $paramObj->product_img
        ];
            $product_pic = $this->mProductPic->insert($aData);
        if($product_pic){
            return true;
        }else{
            return false;
        }

    }

    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 验证码商家入驻
     */
    public function UserSellerJoinEstablishment($paramObj){

     if(empty($paramObj->invite_code)){
         return 0;
     }
        $invitecode =  $this->mInviteCode->InviteCode(['invite_code'=>$paramObj->invite_code]);
       if(!$invitecode){
           return 0;
       }elseif($invitecode->status==2){
           return 2;
       }

        #注册用户
        $aDate = [
            'user_id'              => $paramObj->user_id,
            'status'               => 2,
            'created'              => time()
        ];
        $status = $this->mInviteCode->update($aDate,['invite_code'=>$paramObj->invite_code]);
        #是否注册成功
        if ($status) {
            $this->mUser->update(['is_supplier'=>1],['user_id'=>$paramObj->user_id]);
            $user_info = $this->mUser->GetUserInfo($paramObj->user_id);
            session_put(UserEnum::USER_INFO_USER_ID, $user_info->user_id);
            session_put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
            return 1;
        }


    }


    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 商家入驻信息入库
     */
    public function UserSellerJoinInfo($paramObj){

        #上传图片
        if(!empty($paramObj->operate_license))
            $paramObj->operate_license =  QiniuUpload::instance()->upload_files($paramObj->operate_license);
        if(!empty($paramObj->organization))
            $paramObj->organization =  QiniuUpload::instance()->upload_files($paramObj->organization);
        if(!empty($paramObj->tax_license))
            $paramObj->tax_license =  QiniuUpload::instance()->upload_files($paramObj->tax_license);
        if(!empty($paramObj->account_licence))
            $paramObj->account_licence =  QiniuUpload::instance()->upload_files($paramObj->account_licence);
        #注册用户
        $aDate = [
            'supplier_id'          => $paramObj->user_id,
            'supplier_name'        => $paramObj->supplier_name,
            'company'              => $paramObj->supplier_name,
            'address'              => $paramObj->address,
            'duty_mobile'                => $paramObj->duty_mobile,
            'duty_name'                => $paramObj->duty_name,
            'operate_license'      => $paramObj->operate_license,
            'organization'      => $paramObj->organization,
            'tax_license'      => $paramObj->tax_license,
            'account_licence'      => $paramObj->account_licence,
            'status'              =>  2,
            'created'              => time()
        ];
        if($paramObj->supplier_id){
            $this->mSupplier->update($aDate,['supplier_id'=>$paramObj->supplier_id]);
            #是否注册成功
            return 1;
        }else{
            $status = $this->mSupplier->insert($aDate);
            #是否注册成功
            return 1;
        }




    }

    /**
     * 商家状态
     * @return array
     * @throws Exception
     * @date 2016-6-30
     */
    public function GetSupplierStatus()
    {
        $user_id =session_get(UserEnum::USER_INFO_USER_ID);
        $user_info = $this->mUser->getUserInfo($user_id);
        Session::put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
        $if_supplier = $user_info->is_supplier;
        $supplier_info = $this->mSupplier->GetSupplierDetail($user_id);
        $status = 0;
        if($if_supplier){
            $status = 1;  //已入驻
            if(empty($supplier_info)){
               $status = 11;
            }
        }else{
            if($supplier_info){
                if($supplier_info->status==2){
                    $status = 2; //审核中
                }elseif($supplier_info->status==0){
                    $status = 0;  //审核未通过
                }
            }else{
                $status = 3;  //未入住
            }
        }
        return $status;

    }

    public function GetSupplierInfo($user_id){
       return $this->mSupplier->GetSupplierDetail($user_id);
    }

    /**
     * PC我的订单（全部，待付款，待收货）
     * @author liuyuchao
     * @data 2016-07-01
     */
    public function GetOrderAllPc($user_id ,$status)
    {
        return $this->mOrder->OrderSelectPc($user_id,$status);

    }
    public function DeleteOrder($order_id)
    {

        return $this->mOrder->DeleteOrderPc($order_id);
    }
    //pc确认收货
    public function ConfirmReceipt($order_id)
    {
        return $this->mOrder->ConfirmReceipt($order_id);
    }

    /**
     * 添加购物车
     * @param $paramObj
     * @return int
     * @throws Exception
     * @author
     */
    public function ShopAddCart($paramObj)
    {
        #登录验证
        if (!session_has(UserEnum::USER_INFO_SESSION_KEY))
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $product = $this->mProduct->GetProductById($paramObj->product_id);
        $cart_product = $this->mCart->GetProductId($paramObj->product_id, $user_id);
        #检查库存
        if($cart_product){
            $aWhere = ['product_id' => $paramObj->product_id, 'user_id' => $user_id];
            $status = DB::table('cart')->where($aWhere)->increment('number',$paramObj->number);
            return $status;
        }else{
            #保存数据
            $aData = [
                'user_id'       =>  $user_id,
                'product_id'    =>  $paramObj->product_id,
                'product_name'  =>  empty($product->product_name)?'':$product->product_name,
                'product_sn'    =>  empty($product->product_sn)?'':$product->product_sn,
                'supplier_id'   =>  empty($product->supplier_id)?'':$product->supplier_id,
                'supplier_name'  =>  empty($product->supplier_name)?'':$product->supplier_name,
                'product_img'   =>  empty($product->product_img)?'':$product->product_img,
                'spec_name'     =>  empty($product->spec_name)?'':$product->spec_name,
                'price'         =>  empty($product->price)?'':$product->price,
                'amount'        =>  empty($product->amount)?'':$product->amount,
                'quality_name'  =>  empty($product->quality_name)?'':$product->quality_name,
                'number'        =>  $paramObj->number,
                'level_name'    =>  $product->level,
                'place'         =>  $product->place,
                'unit'          =>  $product->unit,
                'storage'       =>  $product->storage,
                'phone'         =>  $product->phone,
                'created'       =>  time()
            ];

            $result = $this->mCart->insert($aData);
            if(!$result)
                throw new Exception('添加购物车失败', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
            return 1;

        }


    }

    /**
     * 获取购物车列表
     * @return stdClass
     * @throws Exception
     */
    public function ShopCartList()
    {
        #验证登陆
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        #购物车产品列表
        return $this->mCart->GetShopUserCartList($user_id);

    }

    /**
     * 获取购物车商品总和
     * @return stdClass
     * @throws Exception
     */
    public function ShopCartSum()
    {
        #验证登陆
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        #购物车产品总和
        return $this->mCart->GetShopUserCartSum($user_id);

    }

    /**
     * 获取购物车个数
     * @return stdClass
     * @throws Exception
     */
    public function ShopCartCount()
    {
        #验证登陆
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        #购物车产品个数
        return $this->mCart->ShopCartCount($user_id);

    }





    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 个人购物车删除
     */
    public function ShopCartDelete($paramObj){
        if($paramObj->cart_id=='all'){
            $user_id = session_get(UserEnum::USER_INFO_USER_ID);
            $cart_id = $this->mCart->GetShopCartId($user_id);
            $cartid = array();
            foreach($cart_id as $v){
                $cartid[] = $v->cart_id;
            }
            return $this->mCart->ShopCartDeleteAll($cartid);
        }else{
            return $this->mCart->delete(['cart_id' => $paramObj->cart_id]);
        }
    }

    /**
     * 更新购物车
     * @param $paramObj
     * @return fyl
     * @throws Exception
     */
    public function ShopUpdateCart($paramObj)
    {
        #登录验证
        if (!session_has(UserEnum::USER_INFO_SESSION_KEY))
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        $product    =   $this->mProduct->GetProductDetail($paramObj->product_id);
        if($paramObj->product_num > $product->stock)
            return  2;
        $amount     =   number_format($product->price * $paramObj->product_num,2);
        #保存数据
         $this->mCart->update(['number' => $paramObj->product_num,'amount'=> $amount],
            [
                'user_id'   =>  $user_id,
                'product_id' => $paramObj->product_id
            ]);
        return 1;

    }

    /**
     * @param $paramObj
     * @return int
     * @throws Exception
     * 个人购物车删除
     */
    public function HeadCartDelete($paramObj){
        return $this->mCart->delete(['cart_id' => $paramObj->cart_id]);
    }

    /**
     * @param $cart_id
     * @param $user_id
     * @return int
     * @throws Exception
     * 个人订单确认
     */
    public function ShopCartInfo($user_id,$cart_id){
        return $this->mCart->GetCartProducts($user_id,$cart_id);
    }

    /**
     * 订单生成
     * @param $paramObj
     * @return int
     * @throws Exception
     * @author fyl
     * @date 2016-5-12
     */
    public function ShopGenerateOrder($paramObj)
    {
        #登录验证
        if (!session_has(UserEnum::USER_INFO_SESSION_KEY))
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        #获取购物车信息
        $cart_info  =  $this->mCart->GetCartProducts($user_id,$paramObj->cart_id);
        if(empty($cart_info)){
            return false;
        }
        #开始事务
        DB::beginTransaction();
        try{
            $order_sn       =   ToolKit::make_order_sn();
            $order_data = [
                'payment_id'         => $paramObj->pay,                          //支付方式
                'storage'            => $cart_info->storage,                     //仓储地
                'user_id'            => $user_id,                                //用户ID
                'supplier_id'        => $cart_info->supplier_id,                 //商家ID
               // 'address_id'         => $paramObj->address_id,                   //收货地址id
                'order_time'         => time(),                                  //订单生成时间
                'order_sn'           => $order_sn,                               //订单号
                'confirm_time'       => time(),                                  //确认订单时间
                'order_status'       => OrderEnum::STATUS_NO_PAY,                //订单状态
                'start_amount'       => $cart_info->number*$cart_info->price,    //初始总价
                'amount'             => $cart_info->number*$cart_info->price,    //订单总价
                'trade_num'          => 'MTW'.time().rand(100,999),                   //交易流水号
            ];
            $order_id               =   $this->mOrder->insert($order_data);
            if(!$order_id)
                throw new Exception('订单创建失败！', ErrorCodeEnum::STATUS_ERROR);
            $aData = [
                'product_id'    =>  $cart_info->product_id,
                'supplier_id'   =>  $cart_info->supplier_id,
                'order_id'      =>  $order_id,
                'price'         =>  empty($cart_info->price)?'':$cart_info->price,
                'number'        =>   empty($cart_info->number)?'':$cart_info->number,
            ];
            $order_product = $this->mOrderProduct->insert($aData);
            #减库存
            $stock = DB::table('product')
                ->where('product_id',$cart_info->product_i)
                ->where('stock',">=",$cart_info->number)
                ->decrement('stock',$cart_info->number);
            $sales =  DB::table('product')
                ->where('product_id',$cart_info->product_id)
                ->increment('sales', $cart_info->number);
            if(!$order_product || !$sales)
                throw new Exception('订单创建失败！', ErrorCodeEnum::STATUS_ERROR);
            if( !$stock )
                throw new Exception('库存不足！', ErrorCodeEnum::STATUS_ERROR);
            #结束事务
            DB::commit();
            #清空购物车
            $this->mCart->delete(['cart_id' => $paramObj->cart_id]);
            return $order_id;
        } catch(Exception $e){
            #事务回滚
            DB::rollback();
            throw $e;
        }

    }


    /**
     * 订单详情
     * @param $order_id
     * @return array
     * @throws Exception
     * @author alice
     * @date 2016-2-18
     */
    public function OrderDetail($order_id)
    {
        #订单详情
        $order_info = $this->mOrder->GetOrderDetail1($order_id);

        #产品列表
        $order_product = $this->mProduct->GetOrderProductList2($order_info->product_id);
        #地址列表
        $order_adress =  $this->mAddress->GetOrderAddress($order_info->address_id);

        return [
            "order_id"          =>$order_info->order_id,
            "order_sn"          =>$order_info->order_sn,
            "payment_id"          =>$order_info->payment_id,
            "start_amount"          =>$order_info->start_amount,
            "order_time"        =>date('Y-m-d H:i:s',$order_info->order_time),
            "order_status"        =>$order_info->order_status,
            "storage"        =>$order_info->storage,
            "amount"           =>$order_info->amount,
            'product'    =>  $order_product,
            'address'    =>  $order_adress,
        ];

    }
    public function UpdateSelect($address_id){
        return $this->mAddress->UpdateSelect($address_id);

    }
    public function ModifyAddress($paramObj)
    {
        #验证登录
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        #参数验证
        $aData = [
            'is_default'     => $paramObj->is_default,
            'user_id'        => $user_id,
            'consignee'      => $paramObj->consignee,
            'address'        => $paramObj->address,
            'mobile'         => $paramObj->mobile,
            'address_all'    => $paramObj->address_all,
        ];
        #将其他收货地址设置为非默认
        if($paramObj->address_id){
            if($paramObj->is_default==1){
                $this->mAddress->update(['is_default' => UserEnum::CLIENT_USER_OTHER_ADDRESS],['user_id'    => $user_id]);
               // $arr = new stdClass();
                $arr = $this->mAddress->update($aData,['address_id' => $paramObj->address_id]);
                return  $arr;
            }else{
               // $arr = new stdClass();
                $arr = $this->mAddress->update($aData,['address_id' => $paramObj->address_id]);
                return  $arr;
            }
        }else{
            if($paramObj->is_default==1){
                $this->mAddress->update(['is_default' => UserEnum::CLIENT_USER_OTHER_ADDRESS],['user_id'    => $user_id]);
             //   $arr = new stdClass();
                $arr = $this->mAddress->insert($aData);
                return $arr;
            }else{
              //  $arr = new stdClass();
                $arr = $this->mAddress->insert($aData);
                return $arr;
            }
        }
    }


    /**
     * @param $where
     * @return array
     *获取推荐商品ID
     */
    public function AdProduct($where){
        $info = $this->mAdProduct->AdProduct($where);
        foreach($info as $v){
            $ad_product_id[] = $v->product_id;
        }
        return $ad_product_id;
    }

    /**
     * @param $id
     * @return array
     *获取推荐商品详情
     */
    public function AdProductInfo($id){
        return $this->mProduct->AdProductInfo($id);
    }

    /**
     * 发送反馈
     * @param $paramObj
     * @return int
     * @throws Exception
     * @author fyl
     * @date 2016-8-02
     */
    public function SendFeedback($paramObj)
    {
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        if(empty($user_id)){
            return 0;
        }
        #存储数据
        $aData = [
            'user_id'        => $user_id,
            'content'        => $paramObj->content,
            'mobile'         => $paramObj->mobile,
            'created'        => time()
        ];

        return $this->mFeedback->insert($aData);
    }
    /**
     *
     * 用户数据
     */
    public function IndexUser($user_id){

        return $this->mUser->IndexUser($user_id);
    }

}